package com.cskaoyan.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.BaseBusinessException;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    StockMapper stockMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {
        //转型->CreateOrderContext
        CreateOrderContext createOrderContext = (CreateOrderContext) context;

        //得到购物车中的所有商品的id
        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        List<Long> buyProductIds = createOrderContext.getBuyProductIds();
        if (CollectionUtils.isEmpty(buyProductIds)) {
            List<Long> ids = new ArrayList<>();
            for (CartProductDto dto : cartProductDtoList) {
                ids.add(dto.getProductId());
            }
            buyProductIds = ids;
        }
        buyProductIds.sort(Long::compareTo);

        // 锁定库存
        List<Stock> stockList = stockMapper.findStocksForUpdate(buyProductIds);

        // 异常处理
        if (CollectionUtils.isEmpty(stockList)) {
            throw new BizException(OrderRetCode.ALL_PRODUCTS_STOCK_NOT_INIT.getCode(),OrderRetCode.ALL_PRODUCTS_STOCK_NOT_INIT.getMessage());
        }
        if (stockList.size() != buyProductIds.size()) {
            throw new BizException(OrderRetCode.PART_OF_PRODUCTS_STOCK_NOT_INIT.getCode(), OrderRetCode.PART_OF_PRODUCTS_STOCK_NOT_INIT.getMessage());
        }

        // 扣减库存
        for (CartProductDto cartProductDto : cartProductDtoList) {
            Long productId = cartProductDto.getProductId();
            Long productNum = cartProductDto.getProductNum();

            //productNum不能超过限购的数量
            //根据productId查询限购数量
            Stock stockItem = stockMapper.selectStock(productId);
            if (productNum > stockItem.getRestrictCount()) {
                throw new BizException(OrderRetCode.RESTRICT_NUM_EXCEPTION.getCode(), OrderRetCode.RESTRICT_NUM_EXCEPTION.getMessage());
            }

            Stock stock = new Stock();
            stock.setItemId(productId);
            stock.setStockCount(-productNum);
            stock.setLockCount(productNum.intValue());

            stockMapper.updateStock(stock);
        }

        return true;
    }
}